#  -*-  coding: utf-8 -*-

from datetime import datetime
import os
import requests


class TextToSpeech():
    def __init__(self, output_dir):
        self.output_dir = output_dir

    def getSpeech(self, text):
        print('getSpeech from weather text...')
        headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit'
                              '/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safar'
                              'i/537.36',
            }

        url = u'http://tts.baidu.com/text2audio?idx=1&tex={0}&cuid=baidu_speech_' \
              u'demo&cod=2&lan=zh&ctp=1&pdt=1&spd=4&per=4&vol=5&pit=5'.format(text)

        res = requests.get(url, headers=headers)
        if not res.status_code == requests.codes.ok:
            return None

        #print('res=%s' % res.headers)

        t_str = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        mp3_filename = os.path.join(self.output_dir, t_str) + '.mp3'
        print('mp3_filename=%s' % mp3_filename)

        try:
            with open(mp3_filename, 'wb') as f:
                f.write(res.content)
        except Exception as e:
            print('getSpeech Error:%' % e)
            return None

        if not os.path.isfile(mp3_filename):
            return None

        print('getSpeech from weather text finished.')
        return mp3_filename

if __name__ == "__main__":
    tts = TextToSpeech()
    text = "你好"
    s_file= tts.getSpeech(text)
    print('sfile=%s' % s_file)

